//JavaScript代码区域
layui.extend({
  categorySelect: '{/}js/categorySelect' // {/}的意思即代表采用自有路径，即不跟随 base 路径
});
layui.use(['element', 'layer', 'form', 'upload','flow','util','categorySelect'], function () {
    var element = layui.element;
    var layer = layui.layer;
    var form = layui.form;
    var upload = layui.upload;
    var flow = layui.flow;
    var util = layui.util;
    var categorySelect = layui.categorySelect;

    // 点击空白关闭
    $(document).on("click", function(e) {
        var _conss = $('.search-input');//点击的容器范围
        if (!_conss.is(e.target) && _conss.has(e.target).length === 0) {
            $(".search-items").hide();
            $("#search_close").hide();
        }
    });

    var currentPage = 1;// 当前页
    $("#categoryList").empty().next(".layui-flow-more").remove();
    $('#layuiBody').unbind();
    layer.load();
    flow.load({
        elem: '#categoryList'
        ,scrollElem: '#layuiBody'
        ,isLazyimg: true
        ,end: ' '
        ,mb: 400
        ,done: function(page, next){
          // 校正page值
          if(page > 1 && page <= currentPage){
            page = ++currentPage;
            next('',true,currentPage);
          }
          var lis = [];
          $.ajax({
            type: "GET",
            url: "favorites/list",
            data: {"pageNum":page, "pageSize":config.indexPageSize},
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                if(page == 1){
                    layer.closeAll('loading');
                    if(result.code == 0 && result.data.list.length > 0){
                         $("#notFoundDiv").hide();
                    }else{
                         $("#notFoundDiv").show();
                    }
                }
                if (result.code == 0) {
                    // 加载数据
                    $.each(result.data.list, function (i, c) {
                        var html = '';
                        var bookmarkClass = c.bookmark==1?"bookmark":"";
                        html += '<div class="category ' + bookmarkClass + '" data-id="' + c.id + '">';
                        html += '   <div class="title" onclick="editCategory(this,event)">' + escape(c.name) + '</div>';
                        html += '   <ul class="favorites">';
                        if(c.favorites.length > 0) {
                            $.each(c.favorites, function (j, f) {
                                html += '   <li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" data-schema="' + f.schemaName + '" onclick="openUrl(this)">';
                                html += '       <div class="favorites-bg">';
                                html += '           <img src="images/book.svg" lay-src="' + f.icon + '"/>';
                                html += '       </div>';
                                html += '       <p  lay-title="' + escape(f.name) + '">' + escape(f.name) + '</p>';
                                html += '       <i onclick="editFavorites(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                                html += '   </li>';
                                if(j == config.favoritesLimit - 1){
                                    html += '<li class="layui-anim layui-anim-fadein" onclick="moreFavorites(' + c.id + ')">';
                                    html += '   <div class="favorites-bg">';
                                    html += '       <img src="images/more.svg"/>';
                                    html += '   </div>';
                                    html += '   <p lay-title="显示更多">显示更多</p>';
                                    html += '</li>';
                                    return false;
                                }
                            });
                        } else {
                            html += '<li class="layui-anim layui-anim-fadein" onclick="addFavorites(' + c.id + ',\''+ c.name +'\')">';
                            html += '   <div class="favorites-bg">';
                            html += '       <img src="images/add.svg"/>';
                            html += '   </div>';
                            html += '   <p lay-title="添加网址">添加网址</p>';
                            html += '</li>';
                        }
                        html += '   </ul>';
                        html += '</div>';
                        lis.push(html);
                    });
                    next(lis.join(''), page < result.data.pages);
                }
            }
          });
        }
    });

    // 固定块
    util.fixbar({
        top: true
        ,bar1: '&#xe68d;'// 瞬间
        ,bar2: '&#xe637;'// 日历
        ,bar3: '&#xe63c;'// 备忘录
        ,bar4: '&#xe681;'// 文件
        ,scrollElem: '#layuiBody'
        ,bgcolor: '#393D49'
        ,css: {right: windowWidth < 800 ? 30 : 50, bottom: windowWidth < 800 ? 54 : 80}
        ,click: function(type){
            if(type === 'bar1'){
                window.location.href = "moment.html";
            }else if(type === 'bar2'){
                window.location.href = "calendar.html";
            }else if(type === 'bar3'){
                window.location.href = "memorandum.html";
            }else if(type === 'bar4'){
                window.location.href = "file.html";
            }
        }
        ,mouseenter: function(type,ele){
            if(type === 'top'){
                layer.tips('回到顶部', ele, {tips: 4});
            }else if(type === 'bar1'){
                layer.tips('瞬间', ele, {tips: 4});
            }else if(type === 'bar2'){
                layer.tips('日程', ele, {tips: 4});
            }else if(type === 'bar3'){
                layer.tips('备忘录', ele, {tips: 4});
            }else if(type === 'bar4'){
                layer.tips('文件', ele, {tips: 4});
            }
        }
        ,mouseleave: function(ele,type){
            layer.closeAll('tips');
        }
    });

    //执行实例
    var uploadInst = upload.render({
        elem: '#import' //绑定元素
        , accept: 'file'
        , exts: 'xml'
        , size: 51200
        , url: 'favorites/import' //上传接口
        , headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
        , before: function(obj){
            $("#import").html("上传中...").attr("disabled", true);
        }
        , done: function (result) {
            $("#import").html("导入收藏夹").removeAttr("disabled");
            if (result.code == 0) {
                window.location.reload();//刷新
            } else {
                layer.msg(result.msg, {icon: 5});
            }
        }
        , error: function () {
            $("#import").html("导入收藏夹").removeAttr("disabled");
            layer.msg('导入失败', {icon: 5});
        }
        , progress: function(n, elem, e, index){ //注意：index 参数为 layui 2.6.6 新增
            $("#import").html("进度："+ n +"%").attr("disabled", true);
        }
    });

    //执行实例
    var uploadInst1 = upload.render({
        elem: '#importLocal' //绑定元素
        , accept: 'file'
        , exts: 'html'
        , size: 51200
        , url: 'favorites/importHtml' //上传接口
        , headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
        , before: function(obj){
            $("#importLocal").html("上传中...").attr("disabled", true);
        }
        , done: function (result) {
            $("#importLocal").html("从浏览器导入").removeAttr("disabled");
            if (result.code == 0) {
                layer.msg("正在后台导入，请耐心等待...", {icon: 6});
            } else {
                layer.msg(result.msg, {icon: 5});
            }
        }
        , error: function () {
            $("#importLocal").html("从浏览器导入").removeAttr("disabled");
            layer.msg('导入失败', {icon: 5});
        }
        , progress: function(n, elem, e, index){ //注意：index 参数为 layui 2.6.6 新增
            $("#importLocal").html("进度："+ n +"%").attr("disabled", true);
        }
    });

    //执行实例
    var uploadInst2 = upload.render({
        elem: '#importTemplate' //绑定元素
        , accept: 'file'
        , exts: 'xlsx'
        , size: 51200
        , url: 'favorites/importTemplate' //上传接口
        , headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
        , before: function(obj){
            $("#importTemplate").html("上传中...").attr("disabled", true);
        }
        , done: function (result) {
            $("#importTemplate").html("导入模版").removeAttr("disabled");
            if (result.code == 0) {
                layer.msg("正在后台导入，请耐心等待...", {icon: 6});
            } else {
                layer.msg(result.msg, {icon: 5});
            }
        }
        , error: function () {
            $("#importTemplate").html("导入模版").removeAttr("disabled");
            layer.msg('导入失败', {icon: 5});
        }
        , progress: function(n, elem, e, index){ //注意：index 参数为 layui 2.6.6 新增
            $("#importTemplate").html("进度："+ n +"%").attr("disabled", true);
        }
    });

    $("#shortcutMike").click(function(){
        layer.tips('该功能暂未开放', this, {tips: 3});
    });

    $("#searchMike").click(function(){
        layer.tips('该功能暂未开放', this, {tips: 3});
    });

    $("#feedback").click(function(){
      var width = (windowWidth > 800? 800 : windowWidth) - 40 + 'px';
      layer.prompt({
        formType: 2,
        placeholder: '请输入反馈内容',
        title: '我要反馈',
        area: [width, '350px'] //自定义文本域宽高
      }, function(value, index, elem){
        layer.close(index);

        layer.load();
        $.ajax({
            type: "POST",
            url: "user/feedback",
            data: JSON.stringify({"content": value}),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    layer.msg('反馈成功', {icon: 6});
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
      });
    });

    // 清除密码
    $("#unsetPwd").click(function(){
        var passwordId = $("#pwdId").val();
        if(passwordId == ""){
            layer.msg('未设置密码');
            return false;
        }
        layer.confirm('确认清除吗?', function(index){
            layer.close(index);

            layer.load();
            $.ajax({
                type: "DELETE",
                url: "password/" + passwordId,
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        layer.msg('操作成功', {icon: 6});
                        // 重置表单
                        form.val("setting-pwd", {
                            "id": ""
                            , "account": ""
                            , "password": ""
                        });
                    } else {
                       layer.msg(result.msg, {icon: 5});
                    }
                }
            });
        });
    });

    var searchTimer = null;
    $("#catalog_search_name").on("keydown", function (event) {
         // 1.按上下键进入选择模式，并控制，返回键退出选择模式
         // 2.在选择模式时，按下回车跳转超链接，输入值，退出选择模式
         // 3.不在选择模式时，输入框有值，按下回车查询，输入框没有值，按下回车退出查询模式
         if (event.key === "Enter") {
             var activeLi = $(".catalog-li.active")[0];
             if(typeof activeLi !== "undefined"){
                 $(activeLi).click();
             }else{
                 var name = $(this).val().trim();
                 if (name == "") { //退出搜索模式
                     $("#catalog_search_close").click();
                 } else {// 搜索文本
                     loadCatalog(name);
                     searchCount();
                 }
             }
         } else if (event.key === "ArrowDown") {
             var activeLi = $(".catalog-li.active")[0];
             var list = $(".catalog-li");
             if(typeof activeLi === "undefined"){
                 list.eq(0).addClass("active");
             }else{
                 var nextActiveLi;
                 var last;
                 list.each(function(index,item){
                     if($(item).hasClass("active")){
                         var nextIndex = index + 1;
                         nextActiveLi = list[nextIndex];
                         if(nextIndex + 1 === list.length){
                             last = true
                         }
                         return false;
                     }
                 });
                 if(typeof nextActiveLi !== "undefined"){
                     $(activeLi).removeClass("active");
                     $(nextActiveLi).addClass("active");
                     // 滚动
                     if(last){
                         $("#catalog").animate({scrollTop: $("#catalog")[0].scrollHeight}, 50);
                     }else{
                         elasticScroll("#catalog", nextActiveLi.offsetTop);
                     }
                 }
             }
         } else if (event.key === "ArrowUp") {
             var activeLi = $(".catalog-li.active")[0];
             var list = $(".catalog-li");
             if(typeof activeLi === "undefined"){
                 list.eq(0).addClass("active");
             }else{
                 var nextActiveLi;
                 var first;
                 list.each(function(index,item){
                     if($(item).hasClass("active")){
                         var nextIndex = index - 1;
                         nextActiveLi = list[nextIndex];
                         if(nextIndex === 0){
                             first = true;
                         }
                         return false;
                     }
                 });
                 if(typeof nextActiveLi !== "undefined"){
                     $(activeLi).removeClass("active");
                     $(nextActiveLi).addClass("active");
                     // 滚动
                     if(first){
                         $("#catalog").animate({scrollTop: 0}, 50);
                     }else{
                         elasticScroll("#catalog", nextActiveLi.offsetTop);
                     }
                 }
             }
         } else if (event.key === "Backspace") {
             // 退出选择模式
             $(".catalog-li.active").removeClass("active");
         }
     }).on('input',function(){
        var that = $(this);
        $("#catalog_search_close").show();
        clearTimeout(searchTimer); //输入清除定时器
        searchTimer = setTimeout(function () {
            loadCatalog(that.val());
        },250);
    });

    // 关闭搜索
    $("#catalog_search_close").click(function () {
        $(this).hide();
        $("#catalog_search_name").val("");
        loadCatalog();
    });

    window.loadEditUrlInput = function(){
        var url = $("#edit_url_input").val();
        if(url.indexOf("https://") == 0 || url.indexOf("http://") == 0){
            $("#edit_name_input").addClass("layui-disabled").attr("disabled",true);
            $("#edit_url_loading").show();
            // 请求后台解析url
            $.ajax({
                type: "GET",
                url: "favorites/url",
                data: {"url": url},
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    $("#edit_name_input").removeClass("layui-disabled").removeAttr("disabled",true);
                    $("#edit_url_loading").hide();

                    if (result.code == 0) {
                        $("#edit_name_input").val(result.data||"无标题");
                    }
                }
            });
        }
    };

    var searchTimer = null;
    $("#edit_url_input").on('input',function(){
        clearTimeout(searchTimer);
        searchTimer = setTimeout(function(){
            loadEditUrlInput();
        },250);
    });

    window.loadUrlInput = function(){
        var url = $("#url_input").val();
        if(url.indexOf("https://") == 0 || url.indexOf("http://") == 0){
            $("#name_input").addClass("layui-disabled").attr("disabled",true);
            $("#url_loading").show();
            // 请求后台解析url
            $.ajax({
                type: "GET",
                url: "favorites/url",
                data: {"url": url},
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    $("#name_input").removeClass("layui-disabled").removeAttr("disabled",true);
                    $("#url_loading").hide();

                    if (result.code == 0) {
                        $("#name_input").val(result.data||"无标题");
                    }
                }
            });
        }
    };

    var searchTimer = null;
    $("#url_input").on('input',function(){
        clearTimeout(searchTimer);
        searchTimer = setTimeout(function(){
            loadUrlInput();
        },250);
    });

    window.loadNavUrlInput = function(){
        var url = $("#nav_url_input").val();
        if(url.indexOf("https://") == 0 || url.indexOf("http://") == 0){
            $("#nav_name_input").addClass("layui-disabled").attr("disabled",true);
            $("#nav_url_loading").show();
            // 请求后台解析url
            $.ajax({
                type: "GET",
                url: "favorites/url",
                data: {"url": url},
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    $("#nav_name_input").removeClass("layui-disabled").removeAttr("disabled",true);
                    $("#nav_url_loading").hide();

                    if (result.code == 0) {
                        $("#nav_name_input").val(result.data||"无标题");
                    }
                }
            });
        }
    };

    var searchTimer = null;
    $("#nav_url_input").on('input',function(){
        clearTimeout(searchTimer);
        searchTimer = setTimeout(function(){
            loadNavUrlInput();
        },250);
    });

    $("#settingPwd").click(function () {
        layer.open({
            type: 1,
            title: "管理登录此网站的密码",
            content: $('#setting-pwd')
        });
        // 表单赋值
        $.ajax({
            type: "GET",
            url: "password/fid/" + $("#favoritesId").val(),
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                if (result.code == 0 && result.data) {
                    var data = result.data;
                    //给表单赋值
                    form.val("setting-pwd", {
                        "id": data.id
                        , "favoritesId": data.favoritesId
                        , "account": data.account
                        , "password": data.password
                    });
                } else {
                    form.val("setting-pwd", {
                        "id": ""
                        , "favoritesId": $("#favoritesId").val()
                        , "account": ""
                        , "password": ""
                    });
                }
            }
        });
    });

    $("#export").click(function () {
        var favorites = $("#favorites").is(":checked")?"1":"0";
        var moment = $("#moment").is(":checked")?"1":"0";
        var task = $("#task").is(":checked")?"1":"0";
        var search = $("#search").is(":checked")?"1":"0";
        var navigation = $("#navigation").is(":checked")?"1":"0";
        var memorandum = $("#memorandum").is(":checked")?"1":"0";
        layer.close(indexMap.get('#importOrExport'));
        var url = "favorites/export?favorites=" + favorites + "&moment=" + moment + "&task=" + task + "&search=" + search + "&navigation=" + navigation + "&memorandum=" + memorandum;
        downloadFile('export.xml', url);
    });

    $("#exportCategory").click(function () {
        layer.close(indexMap.get('#update-category'));
        var data = form.val("update-category");
        var url = "category/export/" + data.id;
        downloadFile('export_'+ escape(data.name).replace(/\s/g,"_") +'.xml', url);
    });

    $("#cancelPwd").click(function () {
        layer.close(indexMap.get('#changePwd'));
    });

    $("#cancelEmail").click(function () {
        layer.close(indexMap.get('#changeEmail'));
    });

    $("#cancelAddFavorites").click(function () {
        layer.close(indexMap.get('#add-favorites'));
    });

    $("#cancelAddFastNav").click(function () {
        layer.close(indexMap.get('#add-fastNav'));
    });


    // 搜索项绑定点击事件
    $(document).on('click', '.search-items li', function() {
        var text = $(this).text();
        $("#search_name").val(text).focus();
        $(this).parent().hide();
        searchFavorites(text);
    });

    $(document).on('click', '.search-items li .history-close', function(event) {
        layui.stope(event);

        $(this).parent().remove();
        if($(".search-items").children().length === 0) $(".search-items").hide();

        var text = $(this).parent().text();
        var input_history = JSON.parse(localStorage.getItem("input_history"));
        if(input_history.indexOf(text) >= 0) {
            input_history.remove(text);
            localStorage.setItem("input_history", JSON.stringify(input_history));
        }
    });

    $("#importOrExportBtn").click(function () {
        var index = layer.open({
            type: 1,
            area: windowWidth < 800 ? '370px' : '400px',
            title: false,
            closeBtn: 0,
            content: $('#importOrExport')
        });
        indexMap.set('#importOrExport',index);
    });

    // 添加收藏
    $("#addFavoritesBtn").click(function () {
        var index = layer.open({
            type: 1,
            title: "添加收藏",
            area: windowWidth < 800 ? '370px' : '400px',
            skin: 'to-fix-select',
            content: $('#add-favorites')
        });
        indexMap.set('#add-favorites',index);
        // 表单赋值
        form.val("add-favorites", {
            "name": ""
            , "url": ""
            , "isShare": 1
        });
    });

    // 添加快捷导航
    window.addFastNav = function(){
        var index = layer.open({
            type: 1,
            title: "添加快捷导航",
            area: windowWidth < 800 ? '370px' : '400px',
            content: $('#add-fastNav')
        });
        indexMap.set('#add-fastNav',index);
        // 表单赋值
        form.val("add-fastNav", {
            "name": ""
            , "url": ""
        });
    };



    // 快捷导航
    $("#fastNavBtn").click(function () {
        $("#search_name").blur();
        // 弹出层
        var width = (windowWidth > 804 ? 804 : (windowWidth < 360 ? 360 : windowWidth)) + 'px';
        layer.open({
            id: "fastNav",
            type: 1,
            title: "快捷导航",
            area: width,
            content: $("#fastNavDiv"),
            success: function(layero, index){
                loadImg(layero);
            }
        });
    });

    window.loadFastNav = function(){
        $.ajax({
            type: "GET",
            url: "quick-navigation/list",
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                if (result.code == 0) {
                    // 加载数据
                    var html = '   <ul class="favorites" id="dragMenu">';
                    if(result.data.length > 0) {
                        $.each(result.data, function (j, f) {
                            html += '   <li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" data-schema="' + f.schemaName + '" onclick="openNav(this)">';
                            html += '       <div class="favorites-bg">';
                            html += '           <img src="images/book.svg" lay-src="' + f.icon + '"/>';
                            html += '       </div>';
                            html += '       <p  lay-title="' + escape(f.name) + '">' + escape(f.name) + '</p>';
                            html += '       <i onclick="deleteFastNav(this,event)" class="deleteFastNav action-icon layui-icon layui-icon-delete"></i>';
                            html += '   </li>';
                        });
                    }
                    var hideCss = result.data.length < config.navigationLimit ? '' : 'style="display:none"';
                    html += '       <li id="addFastNavBtn" class="layui-anim layui-anim-fadein" onclick="addFastNav()" '+ hideCss +'>';
                    html += '           <div class="favorites-bg">';
                    html += '               <img src="images/add.svg"/>';
                    html += '           </div>';
                    html += '           <p lay-title="添加网址">添加网址</p>';
                    html += '       </li>';
                    html += '   </ul>';
                    $("#fastNavDiv").empty().append(html);
                    // 键盘事件
                    $(document).on("keydown", function (event) {
                        var hidden = $("#fastNavDiv").is(":hidden");
                        if(!hidden){
                            if (event.key === "Enter") {
                                var activeLi = $("#fastNavDiv .favorites-li.active")[0];
                                if(typeof activeLi !== "undefined"){
                                    $(activeLi).click();
                                }
                            } else if (event.key === "ArrowDown") {
                                var activeLi = $("#fastNavDiv .favorites-li.active")[0];
                                var list = $("#fastNavDiv .favorites-li");
                                if(typeof activeLi === "undefined"){
                                    list.eq(0).addClass("active");
                                }else{
                                    var nextActiveLi;
                                    var last;
                                    list.each(function(index,item){
                                        if($(item).hasClass("active")){
                                            var nextIndex = index + 1;
                                            nextActiveLi = list[nextIndex];
                                            if(nextIndex + 1 === list.length){
                                                last = true
                                            }
                                            return false;
                                        }
                                    });
                                    if(typeof nextActiveLi !== "undefined"){
                                        $(activeLi).removeClass("active");
                                        $(nextActiveLi).addClass("active");
                                    }
                                }

                            } else if (event.key === "ArrowUp") {
                                var activeLi = $("#fastNavDiv .favorites-li.active")[0];
                                var list = $("#fastNavDiv .favorites-li");
                                if(typeof activeLi === "undefined"){
                                    list.eq(0).addClass("active");
                                }else{
                                    var nextActiveLi;
                                    var first;
                                    list.each(function(index,item){
                                        if($(item).hasClass("active")){
                                            var nextIndex = index - 1;
                                            nextActiveLi = list[nextIndex];
                                            if(nextIndex === 0){
                                                first = true;
                                            }
                                            return false;
                                        }
                                    });
                                    if(typeof nextActiveLi !== "undefined"){
                                        $(activeLi).removeClass("active");
                                        $(nextActiveLi).addClass("active");
                                    }
                                }
                            } else if (event.key === "Backspace") {
                                // 退出选择模式
                                $("#fastNavDiv .favorites-li.active").removeClass("active");
                            }
                        }
                    });
                    // 初始化拖拽插件
                    var container = document.getElementById("dragMenu");
                    var sort = Sortable.create(container, {
                      handle: ".favorites-bg",
                      draggable: ".favorites-li",
                      onEnd: function (evt){
                         var arr = [];
                         $("#dragMenu .favorites-li").each(function(i,item){
                            var nav = {};
                            nav.id = $(item).attr("data-id");
                            nav.sort = i;
                            arr[i] = nav;
                         });
                         $.ajax({
                            type: "POST",
                            url: "quick-navigation/sort",
                            data: JSON.stringify(arr),
                            contentType: 'application/json;charset=utf-8',
                            dataType: "json",
                            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                            success: function (result) {
                                if (result.code != 0) {
                                    layer.msg(result.msg, {icon: 5});
                                }
                            }
                        });
                      }
                    });
                }
            }
          });
    };
    loadFastNav();

    // 关闭搜索
    $("#search_close").click(function () {
        $(this).hide();
        $("#search_name").val("");
        $(".search-items").hide();
        changeIndexMode();
    });

    // 搜索指令
    window.searchShortcut = function(name){
        layer.load();
        $.ajax({
            type: "GET",
            url: "favorites/shortcut?key=" + name,
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                $("#search_name").val("");
                $("#search_close").hide();
                if (result.data) {
                    $(".favorites-li[data-id=" + result.data.id + "]").click();
                }else{
                    layer.tips('未找到指令', '#search_name', {tips: 1});
                }
            }
        });
    };

    // 切换搜索模式
    window.changeSearchMode = function(){
        $("#dataDiv").hide();
        $("#positionDiv").hide();
        $("#starDiv").hide();
        $("#notFoundDiv").hide();
        $("#searchDiv").show();
    };

    // 切换搜索模式
    window.changePositionMode = function(){
        $("#starDiv").hide();
        $("#dataDiv").hide();
        $("#notFoundDiv").hide();
        $("#searchDiv").hide();
        $("#positionDiv").show();
    };

    // 切换首页模式
    window.changeIndexMode = function(){
        $("#notFoundDiv").hide();
        $("#searchDiv").hide();
        $("#positionDiv").hide();
        $("#starDiv").show();
        $("#dataDiv").show();
    };


    // 搜索文本
    window.searchFavorites = function(name){
        changeSearchMode();
        layer.load();
        $.ajax({
            type: "GET",
            url: "favorites/search",
            data: {"name": name},
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                $("#searchDiv").empty();
                if (result.code == 0 && (result.data.favoritesList.length > 0 || result.data.categoryList.length > 0)) {
                    var html = '';
                    html += '<div class="positionNav">';
                    html += '   <span class="layui-breadcrumb" lay-separator="/" lay-filter="search-nav">';
                    html += '       <a href="javascript:window.location.reload();">首页</a>';
                    html += '       <a><cite>搜索</cite></a>';
                    html += '   </span>';
                    html += '</div>';
                    html += '<ul class="favorites">';
                    $.each(result.data.categoryList, function (i, c) {
                        html += '<li class="favorites-li layui-anim layui-anim-fadein" data-id="' + c.id + '" onclick="showFavorites(this)">';
                        html += '   <div class="favorites-bg">';
                        html += '       <img src="images/category.svg"/>';
                        html += '   </div>';
                        html += '   <p  lay-title="' + escape(c.name) + '">' + escape(c.name) + '</p>';
                        html += '   <i onclick="editCategory(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                        html += '</li>';
                    });
                    $.each(result.data.favoritesList, function (i, f) {
                        html += '<li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" data-schema="' + f.schemaName + '" onclick="openUrl(this)">';
                        html += '   <div class="favorites-bg">';
                        html += '       <img src="images/book.svg" lay-src="' + f.icon + '"/>';
                        html += '   </div>';
                        html += '   <p  lay-title="' + escape(f.name) + '">' + escape(f.name) + '</p>';
                        html += '   <i onclick="editFavorites(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                        html += '</li>';
                    });
                    html += '</ul>';
                    var searchDiv = $("#searchDiv").append(html);
                    loadImg(searchDiv);
                    element.render('breadcrumb', 'search-nav');
                    // 存入历史记录
                    var input_history = JSON.parse(localStorage.getItem("input_history"));
                    if (input_history == null || input_history.length >= 5) input_history = [];
                    if (input_history.indexOf(name) < 0) input_history.push(name);
                    localStorage.setItem("input_history", JSON.stringify(input_history));
                }else{
                    $("#notFoundDiv").show();
                }
            }
        });
    };

    window.showFavorites = function(obj){
        layer.load();
        $.ajax({
            type: "GET",
            url: "category/favorites/" + $(obj).attr("data-id"),
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                $("#searchDiv").empty();
                if (result.code == 0 && result.data.favorites.length > 0) {
                    var c = result.data;
                    var html = '';
                    var bookmarkClass = c.bookmark==1?"bookmark":"";
                    html += '<div class="positionNav">';
                    html += '   <span class="layui-breadcrumb" lay-separator="/" lay-filter="category-nav">';
                    html += '       <a href="javascript:window.location.reload();">首页</a>';
                    html += '       <a><cite>' + escape(c.name) + '</cite></a>';
                    html += '   </span>';
                    html += '</div>';
                    html += '<ul class="favorites ' + bookmarkClass + '">';
                    $.each(c.favorites, function (i, f) {
                        html += '<li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" data-schema="' + f.schemaName + '" onclick="openUrl(this)">';
                        html += '    <div class="favorites-bg">';
                        html += '        <img src="images/book.svg" lay-src="' + f.icon + '"/>';
                        html += '    </div>';
                        html += '    <p  lay-title="' + escape(f.name) + '">' + escape(f.name) + '</p>';
                        html += '    <i onclick="editFavorites(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                        html += '</li>';
                    });
                    html += '</ul>';
                    var searchDiv = $("#searchDiv").append(html).show();
                    loadImg(searchDiv);
                    element.render('breadcrumb', 'category-nav');
                    $("#notFoundDiv").hide();
                }else{
                    $("#notFoundDiv").show();
                }
            }
        });
    };

    initSearch("#search_name");

    // 快捷跳转
    $(document).on("keydown", function(event){
        if(event.ctrlKey && event.key === "q"){
            $("#searchTo").click();
            // 阻止默认浏览器动作(W3C)
            var e = event;
            if ( e && e.preventDefault )
                e.preventDefault();
            // IE中阻止函数器默认动作的方式
            else
                window.event.returnValue = false;
            return false;
        } else if(event.ctrlKey && event.key === "x") {
            $("#fastNavBtn").click();
            // 阻止默认浏览器动作(W3C)
            var e = event;
            if ( e && e.preventDefault )
                e.preventDefault();
            // IE中阻止函数器默认动作的方式
            else
                window.event.returnValue = false;
            return false;
        } else if(event.ctrlKey && event.key === "z") {
            $("#slideBtn").click();
            // 阻止默认浏览器动作(W3C)
            var e = event;
            if ( e && e.preventDefault )
                e.preventDefault();
            // IE中阻止函数器默认动作的方式
            else
                window.event.returnValue = false;
            return false;
        } else if(event.ctrlKey && event.key === "h"){
             window.location.href = "index.html";
             // 阻止默认浏览器动作(W3C)
             var e = event;
             if ( e && e.preventDefault )
                 e.preventDefault();
             // IE中阻止函数器默认动作的方式
             else
                 window.event.returnValue = false;
             return false;
         }
    });

    window.searchCount = function(){
        // 记录搜索次数
        $.ajax({
            type: "GET",
            url: "user/search",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
        });
    };

    window.searchContent = function(){
        var name = $("#search_name").val().trim();
        if (name == "") { //退出搜索模式
            $("#search_close").click();
        } else if(name.indexOf("打开") == 0 || name.indexOf("Open") == 0) { //搜索快捷指令
            searchShortcut(name);
            searchCount();
        } else {// 搜索文本
            searchFavorites(name);
            searchCount();
        }
    };

    $("#searchBtn").click(function(){
        searchContent();
    });

    // 搜索
    $("#search_name").on("keydown", function (event) {
        if (event.key === "Enter") {
            var hidden = $(".search-items").is(":hidden");
            if(!hidden){
                $(".search-items").hide();
            }
            var activeLi = $(".favorites-li.active:visible")[0];
            if(typeof activeLi !== "undefined" && hidden){// 跳转
                $(activeLi).click();
            }else{
                searchContent();
            }
        } else if (event.key === "ArrowDown") {
            // 判断搜索选项是否隐藏，如果隐藏，则进入选择模式
            var hidden = $(".search-items").is(":hidden");
            if(hidden){
                var activeLi = $(".favorites-li.active:visible")[0];
                var list = $(".favorites-li:visible");
                if(typeof activeLi === "undefined"){
                    list.eq(0).addClass("active");
                }else{
                    var nextActiveLi;
                    var last;
                    list.each(function(index,item){
                        if($(item).hasClass("active")){
                            var nextIndex = index + 1;
                            nextActiveLi = list[nextIndex];
                            if(nextIndex + 1 === list.length){
                                last = true
                            }
                            return false;
                        }
                    });
                    if(typeof nextActiveLi !== "undefined"){
                        $(activeLi).removeClass("active");
                        $(nextActiveLi).addClass("active");
                        // 滚动
                        if(last){
                            $("#layuiBody").animate({scrollTop: $("#layuiBody")[0].scrollHeight}, 50);
                        }else{
                            elasticScroll("#layuiBody", nextActiveLi.offsetTop);
                        }
                    }
                }
            }else{
                var hover_in = typeof $(".search-items li.hover-in")[0] === "undefined" ? $(".search-items li:first")[0] : $(
                    ".search-items li.hover-in").next()[0];
                if (typeof hover_in !== "undefined") {
                    $(hover_in).addClass('hover-in').siblings().removeClass('hover-in');
                    $(this).val(hover_in.innerText);
                }else{
                    $(".search-items").hide();
                }
            }
        } else if (event.key === "ArrowUp") {
            // 判断搜索选项是否隐藏，如果隐藏，则进入选择模式
            var hidden = $(".search-items").is(":hidden");
            if(hidden){
                var activeLi = $(".favorites-li.active:visible")[0];
                var list = $(".favorites-li:visible");
                if(typeof activeLi === "undefined"){
                    list.eq(0).addClass("active");
                }else{
                    var nextActiveLi;
                    var first;
                    list.each(function(index,item){
                        if($(item).hasClass("active")){
                            var nextIndex = index - 1;
                            nextActiveLi = list[nextIndex];
                            if(nextIndex === 0){
                                first = true;
                            }
                            return false;
                        }
                    });
                    if(typeof nextActiveLi !== "undefined"){
                        $(activeLi).removeClass("active");
                        $(nextActiveLi).addClass("active");
                        // 滚动
                        if(first){
                            $("#layuiBody").animate({scrollTop: 0}, 50);
                        }else{
                            elasticScroll("#layuiBody", nextActiveLi.offsetTop);
                        }
                    }
                }
            }else{
                var hover_in = typeof $(".search-items li.hover-in")[0] === "undefined" ? $(".search-items li:last")[0] : $(
                    ".search-items li.hover-in").prev()[0];
                if (typeof hover_in !== "undefined") {
                    $(hover_in).addClass('hover-in').siblings().removeClass('hover-in');
                    $(this).val(hover_in.innerText);
                }else{
                    $(".search-items").hide();
                }
            }
        } else if (event.key === "Backspace") {
            // 退出选择模式
            $(".favorites-li.active").removeClass("active");
        }
    }).on("input", function () {
        //退出选择模式
        $(".favorites-li.active").removeClass("active");
    }).on("focus", function () {
       $("#search_close").show();
        var html = '';
        var input_history = JSON.parse(localStorage.getItem("input_history"));
        $.each(input_history, function(index, item) {
            html = '<li>' + item + '<i class="layui-icon layui-icon-close history-close"></i></li>' + html;
        });
        if (html !== "") $(".search-items").empty().append(html).show();
    });
    // 添加收藏
    window.addFavorites = function (categoryId,categoryName) {
        $("#addFavoritesBtn").click();
        $("#categoryId").attr("data-value",categoryId).attr("data-text",categoryName).val(categoryName);
        $("#categoryId-dl").find("dd[lay-value="+ categoryId +"]").addClass("layui-this").siblings().removeClass("layui-this");
    }


    // 弹性滚动
    window.elasticScroll = function(id, height){
        var that = $(id);
        var visibleHeight = that.height();
        var shouldScroll = Math.floor(height/ visibleHeight) * visibleHeight;
        var scrollTop = that.scrollTop();
        if(Math.abs(scrollTop - shouldScroll) >= visibleHeight){
            that.animate({scrollTop: shouldScroll}, 50);
        }
    };

    window.isEmpty = function(obj){
        if(typeof obj == "undefined" || obj == "undefined" || obj == null || obj == "" || obj == "none" || obj == "null"){
            return true;
        }else{
            return false;
        }
    };

    // 打开新窗口
    window.openUrl = function (obj) {
        var url = $(obj).attr("data-url");
        var schema = $(obj).attr("data-schema");
        if(url.indexOf("https://") == 0 || url.indexOf("http://") == 0){
            if(!isEmpty(schema)&&isMobile()){
                layer.confirm('是否打开app？', {
                  btn: ['确认', '取消']
                }, function(index, layero){
                    url = schema + url.substring(url.indexOf("://"));
                    newWin(url);
                    layer.close(index);
                }, function(index){
                    newWin(url);
                    layer.close(index);
                });
            }else{
                newWin(url);
            }
            // 记录访问时间
            $.ajax({
                type: "GET",
                url: "favorites/visit/" + $(obj).attr("data-id"),
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
            });
        }else{
            layer.msg('此链接无效', {icon: 7});
        }
    };

    window.openNav = function (obj) {
        var url = $(obj).attr("data-url");
        if(url.indexOf("https://") == 0 || url.indexOf("http://") == 0){
            newWin(url);
            // 记录访问次数
            $.ajax({
                type: "GET",
                url: "user/visit",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
            });
        }else{
            layer.msg('此链接无效', {icon: 7});
        }
    };

    $("#categorySetTop").click(function(){
        var data = form.val("update-category");
        layer.load();
        $.ajax({
            type: "GET",
            url: "category/setTop/" + data.id,
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
    });

    $("#favoritesSetTop").click(function(){
        var data = form.val("update-favorites");
        layer.load();
        $.ajax({
            type: "GET",
            url: "favorites/setTop/" + data.id,
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
    });

    // 编辑分类
    window.editCategory = function (obj, e) {
        layui.stope(e);
        var index = layer.open({
            type: 1,
            title: "修改分类",
            area: windowWidth < 800 ? '370px' : '400px',
            content: $('#update-category')
        });
        indexMap.set('#update-category',index);
        // 表单赋值
        $.ajax({
            type: "GET",
            url: "category/" + $(obj).parent().attr("data-id"),
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                if (result.code == 0) {
                    let data = result.data;
                    //给表单赋值
                    form.val("update-category", {
                        "id": data.id
                        , "name": data.name
                        , "sort": data.sort
                        , "bookmark": data.bookmark
                        , "count": data.count
                    });
                    //禁用系统分类
                    if (data.isSystem == 1) {
                        $("#categoryName").attr("disabled", true).addClass("layui-disabled");
                        $("#deleteCategory").attr("disabled", true).addClass("layui-btn-disabled");
                    } else if (data.isSystem == 2) {
                         $("#categoryName").attr("disabled", true).addClass("layui-disabled");
                         $("#deleteCategory").removeAttr("disabled").removeClass("layui-btn-disabled");
                    } else {
                        $("#categoryName").removeAttr("disabled").removeClass("layui-disabled");
                        $("#deleteCategory").removeAttr("disabled").removeClass("layui-btn-disabled");
                    }
                }
            }
        });
    };

    // 新增分类
    $("#addCategoryBtn").click(function () {
        layer.prompt({title: "添加分类", placeholder:"输入分类名称", maxlength: 100}, function (value, index, elem) {
            // 验证
            var bool = true;
            $.ajax({
                type: "GET",
                url: 'category/check/' + value,
                async: false,
                dataType: 'json',
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.data) {
                        layer.tips('分类已存在', elem, {tips: 3});
                        bool = false;
                    }
                }
            });
            if(bool){
                layer.close(index);
                layer.load();
                $.ajax({
                    type: "POST",
                    url: "category",
                    data: JSON.stringify({"name": value}),
                    contentType: 'application/json;charset=utf-8',
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        layer.closeAll('loading');
                        if (result.code == 0) {
                            window.location.reload();
                        } else {
                            layer.msg(result.msg, {icon: 5});
                        }
                    }
                });
            }
        });
    });

    // 新增分类
    $("#addCategoryIcon").click(function () {
        layer.prompt({title: "添加分类", placeholder:"输入分类名称", maxlength: 100}, function (value, index, elem) {
            // 验证
            var bool = true;
            $.ajax({
                type: "GET",
                url: 'category/check/' + value,
                async: false,
                dataType: 'json',
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.data) {
                        layer.tips('分类已存在', elem, {tips: 3});
                        bool = false;
                    }
                }
            });
            if(bool){
                layer.close(index);
                layer.load();
                $.ajax({
                    type: "POST",
                    url: "category",
                    data: JSON.stringify({"name": value}),
                    contentType: 'application/json;charset=utf-8',
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        layer.closeAll('loading');
                        if (result.code == 0) {
                            var data = result.data;
                            $("#categoryId").attr("data-value",data.id).attr("data-text",data.name).val(data.name);
                            loadCatalog();
                            categorySelect.loadSelect("#categoryId");
                            categorySelect.loadSelect("#editCategoryId");
                        } else {
                            layer.msg(result.msg, {icon: 5});
                        }
                    }
                });
            }
        });
    });
    
    // 新增分类
    $("#addCategoryIconEdit").click(function () {
        layer.prompt({title: "添加分类", placeholder:"输入分类名称", maxlength: 100}, function (value, index, elem) {
            // 验证
            var bool = true;
            $.ajax({
                type: "GET",
                url: 'category/check/' + value,
                async: false,
                dataType: 'json',
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.data) {
                        layer.tips('分类已存在', elem, {tips: 3});
                        bool = false;
                    }
                }
            });
            if(bool){
                layer.close(index);
                layer.load();
                $.ajax({
                    type: "POST",
                    url: "category",
                    data: JSON.stringify({"name": value}),
                    contentType: 'application/json;charset=utf-8',
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        layer.closeAll('loading');
                        if (result.code == 0) {
                            var data = result.data;
                            $("#editCategoryId").attr("data-value",data.id).attr("data-text",data.name).val(data.name);
                            loadCatalog();
                            categorySelect.loadSelect("#categoryId");
                            categorySelect.loadSelect("#editCategoryId");
                        } else {
                            layer.msg(result.msg, {icon: 5});
                        }
                    }
                });
            }
        });
    });

    window.exportNow = function(){
        $("#export").click();
        layer.closeAll();
    };

    // 清除数据
    $("#cleanData").click(function(){
        var aHtml = '<a class="layui-blue" href="javascript:exportNow();">立即备份</a>';
        layer.confirm('该操作会清除您在平台上的所有数据，且不可恢复，清除数据前应做好备份('+ aHtml +')，谨慎操作！确认清除所有数据吗？', {title:'清除数据'}, function(index){
            layer.close(index);

            layer.prompt({formType: 1, title: "登录密码", placeholder:"请输入登录密码", maxlength: 20}, function(value, index, elem){
                $.ajax({
                    type: "POST",
                    url: "user/cleanData",
                    data: {"loginPwd":md5(value)},
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.code == 0) {
                            window.location.reload();
                        } else {
                            layer.msg(result.msg, {icon: 5});
                        }
                    }
                });
              layer.close(index);
            });
        });
    });

    // 登出
    logout("#logout");

    window.loadCatalog = function(name){
        $("#catalogList").empty().next(".layui-flow-more").remove();
        $('#catalog').unbind();
        flow.load({
            elem: '#catalogList'
            ,scrollElem: '#catalog'
            ,mb: 400
            ,end: ' '
            ,done: function(page, next){
              var lis = [];
              $.ajax({
                    type: "GET",
                    url: "category/page",
                    data: {"pageNum": page,"pageSize": 100,"name":name},
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.code == 0) {
                            $.each(result.data.list, function(index, item){
                                var html = '<li class="catalog-li" onclick="position(' + item.id + ')">' + escape(item.name) + '</li>';
                                lis.push(html);
                            });
                            next(lis.join(''), page < result.data.pages);
                        }
                    }
              });
            }
        });
    };

    // 加载分类
    window.loadCategoryList = function (id) {
        loadCatalog();
        categorySelect.initSelect("#categoryId");
        categorySelect.initSelect("#editCategoryId");
    };
    loadCategoryList();

    window.loadStarFavorites = function () {
        $.ajax({
            type: "GET",
            url: "favorites/star",
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                $("#starDiv").empty();
                if(result.code == 0 && result.data.length > 0){
                    var html = '';
                    html += '<div class="category">';
                    html += '   <div class="title" style="font-size:16px;">常用网址</div>';
                    html += '   <ul class="favorites">';
                    $.each(result.data, function (i, f) {
                        html += '   <li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" data-schema="' + f.schemaName + '" onclick="openUrl(this)">';
                        html += '       <div class="favorites-bg">';
                        html += '           <img src="images/book.svg" lay-src="' + f.icon + '"/>';
                        html += '       </div>';
                        html += '       <p  lay-title="' + escape(f.name) + '">' + escape(f.name) + '</p>';
                        html += '       <i onclick="editFavorites(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                        html += '   </li>';
                    });
                    html += '   </ul>';
                    html += '</div>';

                    var startDiv = $("#starDiv").append(html);
                    loadImg(startDiv);
                }
            }
        });
    };
    loadStarFavorites();

    // 显示更多
    window.moreFavorites = function (categoryId) {
        layer.load();
        $.ajax({
            type: "GET",
            url: "favorites/more",
            data: {"categoryId": categoryId},
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    var html = '';
                    $.each(result.data, function (i, f) {
                        html += '<li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" data-schema="' + f.schemaName + '" onclick="openUrl(this)">';
                        html += '   <div class="favorites-bg">';
                        html += '       <img src="images/book.svg" lay-src="' + f.icon + '"/>';
                        html += '   </div>';
                        html += '   <p  lay-title="' + escape(f.name) + '">' + escape(f.name) + '</p>';
                        html += '   <i onclick="editFavorites(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                        html += '</li>';
                    });
                    var favoritesDiv = $("div[data-id='" + categoryId + "']").find(".favorites").empty().append(html);
                    loadImg(favoritesDiv);
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
    };

    // 删除收藏
    $("#deleteFavorites").click(function () {
        layer.confirm('确认删除收藏吗?', function(index){
            layer.close(index);
            layer.load();
            var data = form.val("update-favorites");
            $.ajax({
                type: "GET",
                url: "favorites/delete/" + data.id,
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    layer.close(indexMap.get('#update-favorites'));
                    if (result.code == 0) {
                        window.location.reload();
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                }
            });
        });
    });

    // 删除快捷导航
    window.deleteFastNav = function(obj, e){
        layui.stope(e);
        layer.confirm('确认删除快捷导航吗?', function(index){
            layer.close(index);
            layer.load();
            $.ajax({
                type: "GET",
                url: "quick-navigation/delete/" + $(obj).parent().attr("data-id"),
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        $(obj).parent().remove();
                        $("#addFastNavBtn").show();
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                }
            });
        });
    };

    // 清空收藏
    $("#clean").click(function () {
        layer.confirm('确认清空分类下所有收藏吗?', function(index){
            layer.close(index);
            layer.load();
            var data = form.val("update-category");
            $.ajax({
                type: "POST",
                url: "category/clean",
                data: {"id": data.id},
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    layer.close(indexMap.get('#update-category'));
                    if (result.code == 0) {
                        window.location.reload();
                    } else {
                        layer.msg(result.msg, {icon: 2});
                    }
                }
            });
        });
    });

    window.deleteAll = function(){
        layer.load();
        var data = form.val("update-category");
        $.ajax({
            type: "GET",
            url: "category/delete/" + data.id,
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                layer.close(indexMap.get('#update-category'));
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 2});
                }
            }
        });
    };

    window.moveDefault = function(){
        layer.load();
        var data = form.val("update-category");
        $.ajax({
            type: "GET",
            url: "category/moveDefault/" + data.id,
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                layer.close(indexMap.get('#update-category'));
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 2});
                }
            }
        });
    };

    // 删除分类
    $("#deleteCategory").click(function () {
        var data = form.val("update-category");
        if(data.count > 0 ){
            layer.open({
              area: ['360px','160px']
              ,title: '删除分类'
              ,content: '该分类下存在书签，确认删除分类吗?'
              ,btn: ['移至默认', '全部删除']
              ,yes: function(index, layero){
                layer.close(index);
                moveDefault();
              }
              ,btn2: function(index, layero){
                layer.close(index);
                deleteAll();
              }
            });
        }else{
            layer.confirm('确认删除分类吗?', function(index){
                layer.close(index);
                deleteAll();
            });
        }
    });

    // 编辑收藏
    window.editFavorites = function (obj, e) {
        layui.stope(e);
        var index = layer.open({
            type: 1,
            title: "修改收藏",
            area: windowWidth < 800 ? '370px' : '400px',
            skin: 'to-fix-select',
            content: $('#update-favorites')
        });
        indexMap.set('#update-favorites',index);
        // 表单赋值
        $.ajax({
            type: "GET",
            url: "favorites/" + $(obj).parent().attr("data-id"),
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                if (result.code == 0) {
                    let data = result.data;
                    $("#editCategoryId").attr("data-value",data.categoryId).attr("data-text",data.categoryName).val(data.categoryName);
                    $("#editCategoryId-dl").find("dd[lay-value="+ data.categoryId +"]").addClass("layui-this").siblings().removeClass("layui-this");
                    //给表单赋值
                    form.val("update-favorites", {
                        "id": data.id
                        , "name": data.name
                        , "url": data.url
                        , "sort": data.sort
                        , "star": data.star
                        , "isShare": data.isShare
                        , "shortcut": data.shortcut
                        , "schemaName": data.schemaName
                    });
                }
            }
        });
    };

    form.verify({
        shortcut: function (value, item) {
            if(value !== ""){
                if(!value.indexOf("打开") == 0 && !value.indexOf("Open") == 0){
                    return '指令请以"打开"或"Open"开头';
                }
                var msg;
                $.ajax({
                    type: "GET",
                    url: 'favorites/shortcut?key=' + value,
                    async: false,
                    dataType: 'json',
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.data && result.data.id != $("#favoritesId").val()) {
                            msg = "指令已存在";
                        }
                    }
                });
                return msg;
            }
        },
        category: function (value, item) {
            if(value.length > 100){
                return "最大限制100个字符";
            }
            var categoryId = form.val("update-category").id;
            var msg;
            $.ajax({
                type: "GET",
                url: 'category/updateCheck/',
                data: {"name":value,"id":categoryId},
                async: false,
                dataType: 'json',
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.data) {
                        msg = "分类已存在";
                    }
                }
            });
            return msg;
        }
    });

    form.on('switch(viewStyle)', function(data){
        if(data.elem.checked){
            $("#layuiBody").addClass("bookmark");
        }else{
            $("#layuiBody").removeClass("bookmark");
        }
        $.ajax({
            type: "POST",
            url: "user/style",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            data: {"viewStyle": data.elem.checked? 1 : 0}
        });
    });

    form.on('switch(starSwitch)', function(data){
        layer.load();
        $.ajax({
            type: "POST",
            url: "favorites/star",
            data: JSON.stringify({"id": $("#favoritesId").val(),"star": data.elem.checked? 1 : 0}),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    layer.msg("操作成功", {icon: 6});
                    loadStarFavorites();
                    // 退出搜索模式
                    $("#search_close").click();
                } else {
                    layer.msg(result.msg, {icon: 5});
                    // 回退
                    $(data.elem).removeAttr("checked");
                    $(data.othis).removeClass("layui-form-onswitch");
                }
            }
        });
    });

    form.on('switch(shareSwitch)', function(data){
        layer.load();
        $.ajax({
            type: "POST",
            url: "favorites/share",
            data: JSON.stringify({"id": $("#favoritesId").val(),"isShare": data.elem.checked? 1 : 0}),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    layer.msg("操作成功", {icon: 6});
                } else {
                    layer.msg(result.msg, {icon: 5});
                    // 回退
                    $(data.elem).removeAttr("checked");
                    $(data.othis).removeClass("layui-form-onswitch");
                }
            }
        });
    });

    form.on('switch(bookmarkSwitch)', function(data){
        var categoryId = form.val("update-category").id;
        layer.load();
        $.ajax({
            type: "POST",
            url: "category/bookmark",
            data: JSON.stringify({"id": categoryId,"bookmark": data.elem.checked? 1 : 0}),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    layer.msg("操作成功", {icon: 6});
                    if(data.elem.checked){
                         $("div[data-id=" + categoryId + "]").addClass("bookmark");
                    }else{
                         $("div[data-id=" + categoryId + "]").removeClass("bookmark");
                    }
                } else {
                    layer.msg(result.msg, {icon: 5});
                    // 回退
                    $(data.elem).removeAttr("checked");
                    $(data.othis).removeClass("layui-form-onswitch");
                }
            }
        });
    });

    // 新增收藏
    form.on('submit(addFavorites)', function (data) {
        data.field.categoryId = $("#categoryId").attr("data-value");
        layer.load();
        $.ajax({
            type: "POST",
            url: "favorites/save",
            data: JSON.stringify(data.field),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                layer.close(indexMap.get('#add-favorites'));
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
        return false;
    });

    // 新增快捷导航
    form.on('submit(addFastNav)', function (data) {
        layer.load();
        $.ajax({
            type: "POST",
            url: "quick-navigation",
            data: JSON.stringify(data.field),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                layer.close(indexMap.get('#add-favorites'));
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
        return false;
    });

    // 保存密码
    form.on('submit(savePwd)', function (data) {
        if(!data.field.account && !data.field.password){
            return false;
        }
        layer.load();
        $.ajax({
            type: "POST",
            url: "password",
            data: JSON.stringify(data.field),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    //给表单赋值
                    form.val("setting-pwd", {
                        "id": result.data
                    });
                    layer.msg("保存成功", {icon: 6});
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
        return false;
    });



    // 修改收藏
    form.on('submit(updateFavorites)', function (data) {
        data.field.categoryId = $("#editCategoryId").attr("data-value");
        layer.load();
        $.ajax({
            type: "POST",
            url: "favorites/save",
            data: JSON.stringify(data.field),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                layer.close(indexMap.get('#update-favorites'));
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
        return false;
    });

    // 修改分类
    form.on('submit(updateCategory)', function (data) {
        layer.load();
        $.ajax({
            type: "POST",
            url: "category",
            data: JSON.stringify(data.field),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                layer.close(indexMap.get('#update-category'));
                if (result.code == 0) {
                    window.location.reload();
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
        return false;
    });


    // 搜索项绑定hover事件
    $(document).on('mouseenter', '.search-items li', function() {
        $(this).addClass('hover-in');
    });

    $(document).on('mouseleave', '.search-items li', function() {
        $(this).removeClass('hover-in');
    });

    window.position = function(id){
        changePositionMode();
        layer.close(indexMap.get('#catalog'));
        layer.load();
        $.ajax({
            type: "GET",
            url: "favorites/position/" + id,
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    // 加载数据
                    var c = result.data;
                    var html = '';
                    var bookmarkClass = c.bookmark==1?"bookmark":"";
                    html += '<div class="category ' + bookmarkClass + '" data-id="' + c.id + '">';
                    html += '   <div class="title" onclick="editCategory(this,event)">' + escape(c.name) + '</div>';
                    html += '   <ul class="favorites">';
                    if(c.favorites.length > 0) {
                        $.each(c.favorites, function (j, f) {
                            html += '   <li class="favorites-li layui-anim layui-anim-fadein" data-id="' + f.id + '" data-url="' + f.url + '" data-schema="' + f.schemaName + '" onclick="openUrl(this)">';
                            html += '       <div class="favorites-bg">';
                            html += '           <img src="images/book.svg" lay-src="' + f.icon + '"/>';
                            html += '       </div>';
                            html += '       <p  lay-title="' + escape(f.name) + '">' + escape(f.name) + '</p>';
                            html += '       <i onclick="editFavorites(this,event)" class="action-icon layui-icon layui-icon-more-vertical"></i>';
                            html += '   </li>';
                            if(j == config.favoritesLimit - 1){
                                html += '<li class="layui-anim layui-anim-fadein" onclick="moreFavorites(' + c.id + ')">';
                                html += '   <div class="favorites-bg">';
                                html += '       <img src="images/more.svg"/>';
                                html += '   </div>';
                                html += '   <p lay-title="显示更多">显示更多</p>';
                                html += '</li>';
                                return false;
                            }
                        });
                    } else {
                        html += '<li class="layui-anim layui-anim-fadein" onclick="addFavorites(' + c.id + ',\''+ c.name +'\')">';
                        html += '   <div class="favorites-bg">';
                        html += '       <img src="images/add.svg"/>';
                        html += '   </div>';
                        html += '   <p lay-title="添加网址">添加网址</p>';
                        html += '</li>';
                    }
                    html += '   </ul>';
                    html += '</div>';
                    var positionData = $("#positionData").empty().append(html);
                    loadImg(positionData);
                }
            }
        });
    };

    window.showLink = function(linkUrl,linkName){
        var dom = $(".favorites-link").show();
        dom.find(".link-url").text(linkUrl);
        dom.find(".link-name").text(linkName);
        localStorage.setItem("favorites_link_url",linkUrl);
        localStorage.setItem("favorites_link_name",linkName);
        localStorage.setItem("favorites_link_cancel",false);
        localStorage.setItem("favorites_link_save",false);
    };

    window.parseLink = function(text){
        var link = {};
        if(text && text.indexOf("http") != -1){
            var index = text.indexOf("http");
            link.url = text.substring(index);
            link.name = text.substring(0,index);
            if(!link.name){
                $.ajax({
                    type: "GET",
                    async: false,
                    url: "favorites/url",
                    data: {"url": link.url},
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.code == 0) {
                            link.name = result.data||"无标题";
                        }
                    }
                });
            }
        }
        return link;
    };

    window.loadLink = function(){
        navigator.clipboard&&navigator.clipboard.readText().then((text) => {
            var favoritesLinkUrl = localStorage.getItem("favorites_link_url");
            var favoritesLinkName = localStorage.getItem("favorites_link_name");
            var favoritesLinkCancel = localStorage.getItem("favorites_link_cancel");
            var favoritesLinkSave = localStorage.getItem("favorites_link_save");
            // 获取新外链
            var link = parseLink(text);
            var linkUrl = data.url;
            var linkName = data.title;
            // 如有有新外链，展示新外链，否则展示旧外链
            if(linkUrl && linkUrl != favoritesLinkUrl){
                showLink(linkUrl,linkName);
            }else if(favoritesLinkUrl && favoritesLinkSave != 'true' && favoritesLinkCancel != 'true'){
                showLink(favoritesLinkUrl,favoritesLinkName);
            }
        }, (error) => { console.log(error) })
    };

    window.loadUserInfo = function(){
        $.ajax({
            type: "GET",
            url: "user/info",
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                if (result.code == 0) {
                    var user = result.data;
                    if(!user.nickName){
                        window.location.href = "set_user_info.html";
                    }
                    $("#username").text(user.nickName);
                    form.val("styleSelect", {"viewStyle": user.viewStyle});
                    if(user.viewStyle == 1)$("#layuiBody").addClass("bookmark");
                    if(user.searchStyle == 1)$("#searchDiv").addClass("bookmark");
                    if(user.favoriteLink == 1)loadLink();
                }
            }
        });
    };
    loadUserInfo();

    window.initClipboard = function(){
        var clipboard = new ClipboardJS('#accountCopy');
        clipboard.on('success', function(e) {layer.msg("复制成功");});
        clipboard.on('error', function(e) {layer.msg("复制失败");});

        var clipboard1 = new ClipboardJS('#passwordCopy');
        clipboard1.on('success', function(e) {layer.msg("复制成功");});
        clipboard1.on('error', function(e) {layer.msg("复制失败");});

        var clipboard2 = new ClipboardJS('#edit_url_input_copy');
        clipboard2.on('success', function(e) {layer.msg("复制成功");});
        clipboard2.on('error', function(e) {layer.msg("复制失败");});
    };
    initClipboard();

    $("#slideBtn").click(function(){
        var width = (windowWidth > 500 ? 500 : (windowWidth < 340 ? 340 : windowWidth)) + 'px';
        var index = layer.open({
            id: "catalog-layer", // 防止弹出框重复弹出
            type: 1,
            title: "目录",
            area: [width, '300px'],
            content: $("#catalog")
        });
        indexMap.set('#catalog',index);
        $("#catalog_search_name").focus();
    });

    // 回收站
    $("#recycle").click(function() {
        var width = (windowWidth > 800? 800 : windowWidth) + 'px';
        var index = layer.open({
            type: 2,
            area: [width,'530px'],
            title: false,
            closeBtn: 0,
            scrollbar: false,
            content: ['recycle.html?' + timeSuffix(),'no']
        });
        indexMap.set('#recycle',index);
    });

    // 个人信息
    $("#info").click(function() {
        var width = (windowWidth > 800? 800 : windowWidth) + 'px';
        var index = layer.open({
            type: 2,
            area: [width,'530px'],
            title: false,
            closeBtn: 0,
            scrollbar: false,
            content: 'user_info.html?' + timeSuffix()
        });
        indexMap.set('#info',index);
    });

    // 报告
    $("#report").click(function() {
        var width = (windowWidth > 800? 800 : windowWidth) + 'px';
        var index = layer.open({
            type: 2,
            area: [width,'530px'],
            title: false,
            closeBtn: 0,
            content: 'report.html?' + timeSuffix()
        });
        indexMap.set('#report',index);
    });

    $("#searchTo").click(function(){
        localStorage.setItem("jumpSearch", $("#search_name").val());
        window.location.href = "search.html";
    });

    window.showNotice = function(type){
        // 查询公告
        // 若有公告，按钮展示，点击显示公告，若未读，弹出公告，
        // 若无公告，按钮隐藏
        $.ajax({
            type: "GET",
            url: "user/notice",
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                var data = result.data||{};
                if (data.isShow) {
                    var title = data.title;
                    var content = data.content;
                    var noticeId = data.id;
                    // 显示按钮
                    $("#notice").click(function(){
                        var width = (windowWidth > 800 ? 800 : windowWidth) + 'px';
                          layer.open({
                            type: 1
                            ,title: false
                            ,closeBtn: false
                            ,area: width
                            ,shade: 0.8
                            ,id: 'LAY_NOTICE'
                            ,btn: '知道了'
                            ,btnAlign: 'c'
                            ,moveType: 1
                            ,content: '<div class="notice-panel">'+ content +'</div>'
                            ,yes: function(index, layero){
                                layer.close(index);
                                localStorage.setItem("noticeId", noticeId);
                            }
                          });
                    }).show().find("em").text(title);
                    // 弹出公告
                    if(localStorage.getItem("noticeId") != noticeId){
                        $("#notice").click();
                    }
                }else{
                    $("#notice").hide().click(function(){
                        layer.alert('暂无公告！', {icon: 0});
                    });
                }
            }
        });
    };
    showNotice();

    // 定时器
    window.onlineCount = function(){
        $.ajax({
            type: "GET",
            url: "user/online",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")}
        });
    };
    setInterval(onlineCount(),3600000);

    window.saveLink = function(){
        var dom = $(".favorites-link").hide();
        var linkUrl = dom.find(".link-url").text();
        var linkName = dom.find(".link-name").text();
        if(linkUrl&&linkName){
            layer.load();
            $.ajax({
                type: "POST",
                url: "favorites/saveLink",
                data: JSON.stringify({"url":linkUrl,"name":linkName}),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        localStorage.setItem("favorites_link_save", true);
                        window.location.reload();
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                }
            });
        }
    };

    $("#importBtn").click(function(){
        // 关闭导入弹窗
        layer.close(indexMap.get('#importOrExport'));
        // 弹出模版导入弹窗
        var index = layer.open({
            type: 1,
            area: windowWidth < 800 ? '370px' : '400px',
            title: "模版导入",
            content: $("#templateDiv"),
        });
        indexMap.set('#importTemplate', index);
    });

    $("#downloadTemplate").click(function(){
        layer.close(indexMap.get('#importTemplate'));
        var url = "favorites/downloadTemplate/";
        downloadFile('template.xlsx', url);
    });

    window.cancelLink = function(){
        var dom = $(".favorites-link").hide();
        localStorage.setItem("favorites_link_cancel", true);
    };

    $("#addLinkBtn").click(function(){
        var width = (windowWidth > 500? 500 : windowWidth) - 40 + 'px';
        layer.prompt(
            {
                title: "链接收藏",
                placeholder:"请输入链接地址",
                maxlength: 2000,
                area: [width,'34px'],
                btn: ['保存', '取消']
            }, function (value, index, elem) {
              var link = parseLink(value);
              if(link.url&&link.name){
                layer.close(index);
                layer.load();
                $.ajax({
                      type: "POST",
                      url: "favorites/saveLink",
                      data: JSON.stringify(link),
                      contentType: 'application/json;charset=utf-8',
                      dataType: "json",
                      headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                      success: function (result) {
                          layer.closeAll('loading');
                          if (result.code == 0) {
                              window.location.reload();
                          } else {
                              layer.msg(result.msg, {icon: 5});
                          }
                      }
                });
              }else{
                layer.tips('无效链接', elem, {tips: 3});
              }
        });
    });
});